import { defineStore } from 'pinia'
import { PLAY_MODE } from '@/enum'
import { showToast } from 'vant'
import { processSongUrl, shuffle } from '@/utils'
import { __PLAY_MODE_KEY__, __TOP_LIST_KEY__ } from '@/utils/constant'
import { getToplist } from '@/api/ranking'
import { getSongSheetSongList } from '@/api/recommend'
import { getSongUrl } from '@/api/common'
type initState = {
  playlist: ISongItem[]
  sequenceList: ISongItem[]
  favoriteList: ISongItem[]
  topList: ITopItem[]
  topListDataLoadingSuccess: boolean
  currentIndex: number
  playing: boolean
  fullScreen: boolean
  playMode: PLAY_MODE
  showSearch: boolean
}
export const usePlayerStore = defineStore('playerStore', {
  // 推荐使用 完整类型推断的箭头函数
  state: (): initState => {
    return {
      sequenceList: [],
      playlist: [],
      playing: false,
      playMode: Number(localStorage.getItem(__PLAY_MODE_KEY__)) || PLAY_MODE.SEQUENCE,
      currentIndex: -1,
      fullScreen: false,
      favoriteList: [],
      topList: [],
      topListDataLoadingSuccess: false,
      showSearch: false
      // searchHistory: load(SEARCH_KEY),
      // playHistory: []
    }
  },
  getters: {
    currentSong: (state): ISongItem => {
      return state.playlist[state.currentIndex]
    },
    // 播放模式对应的icon图标
    playModeIcon: (state): string => {
      const mode = state.playMode
      return mode === PLAY_MODE.SEQUENCE
        ? 'icon-sequence'
        : mode === PLAY_MODE.LOOP
        ? 'icon-loop'
        : 'icon-random'
    },
    // 播放模式对应的文本
    playModeText: (state): string => {
      return state.playMode === PLAY_MODE.SEQUENCE
        ? '顺序播放'
        : state.playMode === PLAY_MODE.LOOP
        ? '单曲循环'
        : '随机播放'
    }
  },
  actions: {
    // 播放音乐
    playMusic(song: ISongItem, songs: ISongItem[]) {
      const currentIndex = songs.findIndex((item) => item.id === song.id)
      this.playing = true
      this.sequenceList = songs
      this.playlist = songs
      this.currentIndex = currentIndex
      this.fullScreen = true
    },
    // 设置播放模式
    setPlayMode() {
      const mode = (this.playMode = (this.playMode + 1) % 3)
      const currentSong = this.playlist[this.currentIndex]
      if (mode === PLAY_MODE.RANDOM) {
        this.playlist = shuffle<ISongItem>(this.sequenceList)
      } else {
        this.playlist = this.sequenceList
      }
      this.currentIndex = this.playlist.findIndex((song) => song.id === currentSong.id)
      this.playMode = mode
      localStorage.setItem(__PLAY_MODE_KEY__, String(mode))
      const text =
        mode === PLAY_MODE.SEQUENCE ? '顺序播放' : mode === PLAY_MODE.LOOP ? '单曲循环' : '随机播放'
      showToast(text)
    },
    removeSong(song: ISongItem) {
      const sequenceList = this.sequenceList.slice()
      const playlist = this.playlist.slice()
      const sequenceIndex = findIndex(sequenceList, song)
      const playIndex = findIndex(playlist, song)
      if (sequenceIndex < 0 || playIndex < 0) {
        return
      }
      sequenceList.splice(sequenceIndex, 1)
      playlist.splice(playIndex, 1)
      let currentIndex = this.currentIndex
      if (playIndex < currentIndex || currentIndex === playlist.length) {
        currentIndex--
      }
      this.sequenceList = sequenceList
      this.playlist = playlist
      this.currentIndex = currentIndex
      if (!playlist.length) {
        this.playing = false
      }
    },
    // 清除歌曲列表
    clearPlayList() {
      this.sequenceList = []
      this.playlist = []
      this.currentIndex = -1
      this.playing = false
    },
    async getTopList() {
      this.topListDataLoadingSuccess = true
      const cacheList = JSON.parse(sessionStorage.getItem(__TOP_LIST_KEY__) || 'null')
      if (cacheList && Array.isArray(cacheList) && cacheList.length > 0) {
        this.topListDataLoadingSuccess = false
        this.topList = cacheList
        return
      }
      const list = (await getToplist()).list.slice(0, 10)
      for (let i = 0; i < list.length; i++) {
        const songs = (list[i].songs = (await getSongSheetSongList(list[i].id)).songs)
        const ids = songs.map(({ id }) => id)
        const { data } = await getSongUrl(ids)
        // 根据歌曲id获取到对应的url播放地址
        processSongUrl(songs, data)
      }
      sessionStorage.setItem(__TOP_LIST_KEY__, JSON.stringify(list))
      this.topList = list
      this.topListDataLoadingSuccess = false
    },
    addSongToPlaylist(song: ISongItem) {
      let currentIndex = this.currentIndex
      const playlist = this.playlist.slice()
      const sequenceList = this.sequenceList.slice()
      const playlistIndex = findIndex(playlist, song)
      const sequenceListIndex = findIndex(sequenceList, song)
      if (playlistIndex > -1) {
        currentIndex = playlistIndex
      } else {
        playlist.push(song)
        currentIndex = playlist.length - 1
      }
      if (sequenceListIndex === -1) {
        sequenceList.push(song)
      }
      this.playlist = playlist
      this.sequenceList = sequenceList
      this.currentIndex = currentIndex
    }
  }
})

function findIndex<T extends ISongItem>(list: T[], song: T): number {
  return list.findIndex((item) => {
    return item.id === song.id
  })
}
